package com.emep.changzhi.analyse.service.systeminfo;

import com.emep.changzhi.analyse.config.RedisClient;
import com.emep.changzhi.analyse.entity.systeminfo.SysRoleInfo;
import com.emep.changzhi.analyse.entity.systeminfo.SysUserInfo;
import com.emep.changzhi.analyse.repository.basics.SysAreaInfoRepository;
import com.emep.changzhi.analyse.repository.systeminfo.SysRoleInfoRepository;
import com.emep.changzhi.analyse.repository.systeminfo.SysUserInfoRepository;
import com.emep.changzhi.analyse.utils.GsonUtils;
import com.emep.changzhi.analyse.utils.MapUtils;
import com.emep.changzhi.analyse.utils.StringUtils;
import com.emep.changzhi.analyse.utils.UUIDTest;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @author Wangcc
* @Description: 用户业务层，依赖持久层  SysUserInfoService
* @date 2018/2/23 13:47
* @version V1.0
*/
@Slf4j
@Service
public class SysUserInfoService {

    @Resource
    private SysUserInfoRepository sysUserInfoRepository;

    @Resource
    private SysRoleInfoRepository sysRoleInfoRepository;

    @Resource
    private SysAreaInfoRepository areaInfoRepository;

    @Autowired
    private RedisClient redisClient;
    /**
     *
     * 不含查询条件的分页获取数据
     *
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public Page<SysUserInfo> findAll(Integer pageNo, Integer pageSize){
        Map<String,Object> map = new HashMap<>();
        try {
            Pageable pageable = new PageRequest(pageNo-1, pageSize);
            return sysUserInfoRepository.findAll(pageable);
        } catch (Exception e) {
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
            return null;
        }
    }

    /**
     *
     * 新增用户
     *
     * @param payload
     * @return
     * @throws Exception
     */
    public SysUserInfo saveAndRole(Map<String, Object> payload) {
        SysUserInfo sysUserInfo = new SysUserInfo();
        Set<SysRoleInfo> sysRoleInfos = new HashSet<>();
        try {
            SysUserInfo sysUserInfo1 = (SysUserInfo) MapUtils.convertMap(SysUserInfo.class,payload);
            //遍历角色id
            if(payload.containsKey("roleId")){
                String roleIds = payload.get("roleId").toString();
                SysRoleInfo sysRoleInfo = sysRoleInfoRepository.findSysRoleInfoById(roleIds);
                sysRoleInfos.add(sysRoleInfo);
                sysUserInfo1.setSysRoleInfos(sysRoleInfos);
            }
            sysUserInfo = sysUserInfoRepository.save(sysUserInfo1);
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return sysUserInfo;
    }




    /**
     *
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    public SysUserInfo findId(String id){
        SysUserInfo sysUserInfo = null;
        try {
            sysUserInfo = sysUserInfoRepository.findSysUserInfoById(id);
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return sysUserInfo;
    }

    /**
     *
     * 检查手机号是否合法
     *
     * @param phone
     * @return
     */
    public String islegal(String phone){
        SysUserInfo sysUserInfo = null;
        String res="";
        try {
            sysUserInfo = sysUserInfoRepository.findSysUserInfoByPhone(phone);
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }

        if(sysUserInfo ==null){
            res="请联系管理员";
        }
        return res;
    }

    /**
     *
     * 根据id 删除用户
     *
     * @param id
     */
    public Boolean deleteUser(String id) {
        Boolean result = false;
        try {
          Integer  result1 = sysUserInfoRepository.deleteSysUserInfoById(id);
          if(result1 == 1){
              result = true;
          }
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return result;
    }

    /**
     *查询所有用户
     *
     * @return
     */
    public List<SysUserInfo> findAllUsers() {
        List<SysUserInfo> sysUserInfos = null;
        try {
            sysUserInfos =  sysUserInfoRepository.findAll();
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return sysUserInfos;
    }


    /**
     *
     * @param page 页数
     * @param size 数量
     * @param sysUserInfo 参数
     * @return
     */
    public Page<SysUserInfo> findBookCriteria(Integer page, Integer size, SysUserInfo sysUserInfo) {
        //规格定义页码：前端从1开始，jpa从0开始，做个转换
        Pageable pageable = new PageRequest(page-1,size , Sort.Direction.ASC, "id");
        Page<SysUserInfo> studentPage = sysUserInfoRepository.findAll(new Specification<SysUserInfo>(){
            @Override
            public Predicate toPredicate(Root<SysUserInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate p1 = criteriaBuilder.equal(root.get("phone").as(String.class), sysUserInfo.getPhone());
                query.where(criteriaBuilder.and(p1));
                return query.getRestriction();
            }
        },pageable);
        return studentPage;
    }


    /**
     *
     * 登录
     *
     * @param phone
     * @param captcha
     * @param session
     * @return
     */
    public String login(String phone,String captcha,HttpSession session){
        String token = "";
        //获取到验证码
        String s_captcha = redisClient.get(phone);
        if (!StringUtils.isEmpty(s_captcha) && captcha.equals(s_captcha)){
            try {
                token = UUIDTest.getUUID()+System.currentTimeMillis();
//                OkHttpClient client = new OkHttpClient.Builder()
//                        .connectTimeout(5, TimeUnit.SECONDS)
//                        .writeTimeout(10, TimeUnit.SECONDS)//写入超时
//                        .readTimeout(5, TimeUnit.SECONDS)
//                        .build();
//                Request request = new Request.Builder()
//                        .url("http://localhost:9999/oauth/token?grant_type=password&username=" + phone + "&password=" + captcha +
//                                "&client_id=xieyang&client_secret=123456")
//                        .build();
//                Response response = null;
//                response = client.newCall(request).execute();
//                if (response.isSuccessful()) {
//                    log.info("***************** 【创建Token 请求成功】 请求状态:=={}", response.code());
//                    Map<String, Object> map = GsonUtils.changeGsonToMaps(response.body().string());
//                    token = map.get("access_token").toString();
                    SysUserInfo sysUserInfo=findByPhone(phone);
                    session.setAttribute(token,sysUserInfo);
                    //session过期时间为24小时
                    session.setMaxInactiveInterval(60*60*24);
//                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return token;
    }

    /**
     *  通过手机号查询用户信息
     * @param phone
     * @return
     */
    public SysUserInfo findByPhone(String phone ){
        return sysUserInfoRepository.findSysUserInfoByPhone(phone);
    }


     /** 添加用户手机号
     * @param payload
     * @return
     */
    public SysUserInfo saveUser(Map<String, Object> payload) {
        SysUserInfo sysUserInfo = new SysUserInfo();
        String 	userName = payload.get("name") != null ? payload.get("name").toString() : "";
        try {
            SysUserInfo sysUserInfo1 = (SysUserInfo) MapUtils.convertMap(SysUserInfo.class,payload);
            sysUserInfo1.setUserName(userName);
            sysUserInfo = sysUserInfoRepository.save(sysUserInfo1);
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return sysUserInfo;
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @param session
     * @return
     */
    public SysUserInfo findUserByToken(String token, HttpSession session) {
        SysUserInfo sysUserInfo = new SysUserInfo();
        sysUserInfo = (SysUserInfo) session.getAttribute(token);
        return sysUserInfo;
    }

    /**
     * 根据token获取用户信息
     * @param payload
     * @param session
     * @return
     */
   /* public SysUserInfo findUserByToken(String payload, HttpSession session) {
        SysUserInfo sysUserInfo = new SysUserInfo();
        SysUserInfo sysUserInfo1 = new SysUserInfo();
        String 	token= payload.get("token") != null ? payload.get("token").toString() : "";
        sysUserInfo1.setUserName("用户1");
        session.setAttribute("123",sysUserInfo1);
        sysUserInfo = (SysUserInfo) session.getAttribute(token);
        return sysUserInfo;
    }*/

}
